import * as api from '../../api/common';
import drawQrcode from '../../utils/qr.js'

Page({
  data: {
    activities: [],
    loading: false,
    hasMore: true, // 初始假设有更多数据
    pageNum: 1,
    pageSize: 10,
    hidden: true,
    searchName: '',
    statusBarHeight: 0,
    height: 0,
    ticketId: null,
    qrWidth: 0
  },
  onLoad(options) {
    const sysInfo = tt.getMenuButtonBoundingClientRect();
    this.setData({
      height: sysInfo.height,
      statusBarHeight: sysInfo.top,
      ticketId: options.id,
    });
    this.loadData();  // 加载初始数据
    const qrWidth = 260 / 750 * tt.getSystemInfoSync().safeArea.width;

    this.setData({
      qrWidth: qrWidth
    })
  },
  async onInputChange(e) {
    const value = e.detail.value;
    this.setData({
      searchName: value,
      activities: [],
      pageNum: 1, // 重置页码
      hasMore: true, // 重新加载时假设有更多数据
    });
    await this.loadData(); // 搜索时重新加载数据
  },
  // 长按扫码处理函数
  longPressScan(event) {
    tt.scanCode({
      success: (res) => {
        console.log('扫码成功', res);
        // 可以根据扫码结果进行业务处理，比如展示扫描到的内容
        tt.showToast({
          title: '扫描成功',
          icon: 'success'
        });
      },
      fail: (res) => {
        console.log('扫码失败', res);
        tt.showToast({
          title: '扫描失败，请重试',
          icon: 'none'
        });
      }
    });
  },
  openMask(e) {
    let code = e.currentTarget.dataset.code
    let status = e.currentTarget.dataset.status
    if (status == 1) {
      return
    }
    this.setData({
      hidden: false
    })
    setTimeout(() => {
      drawQrcode({
        width: this.data.qrWidth,
        height:  this.data.qrWidth,
        canvasId: 'qr',
        text: code,
        // image: {
        //   imageResource: '../../images/icon.png',
        //   dx: 70,
        //   dy: 70,
        //   dWidth: 60,
        //   dHeight: 60
        // }
      })
    }, 0)
  },
  closeMask() {
    this.setData({
      hidden: true
    })
  },
  saveImageToPhotosAlbum() {
    tt.canvasToTempFilePath({
      canvasId: 'qr',
      success: (res) => {
        tt.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res2) {
            tt.showToast({
              title: '保存成功'
            });
          },
          fail(res2) {}
        });
      },
      fail: (res) => {
        console.log("downloadFile fail", res);
        tt.showToast({
          title: res.errMsg,
          icon: "none",
        });
      },
    })
    return;
    tt.downloadFile({
      url: "http://43.137.16.241:9020/assets/img/brand/Logo.png",
      header: {
        "content-type": "application/json",
      },
      success: (res) => {
        console.log("downloadFile success", res);
        tt.showToast({
          title: res.errMsg,
          icon: "success",
        });
        tt.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res2) {
            console.log("下载成功", res2);
          },
          fail(res2) {
            console.log(res2);
          }
        });
      },
      fail: (res) => {
        console.log("downloadFile fail", res);
        tt.showToast({
          title: res.errMsg,
          icon: "none",
        });
      },
      complete: (res) => {
        console.log("downloadFile complete", res);
      },
    });

  },
  async loadData(pageNum = 1) {
    const userId = tt.getStorageSync('info').id;
    const { searchName, pageSize, ticketId } = this.data;
    const params = {
      id: ticketId,
      userId,
      name: searchName,
      pageSize,
      pageNum,
    };

    this.setData({ loading: true });

    try {
      const response = await api.ticketFolderInfo(params);
      const moreData = response.data.data;
      const totalPage = response.data.last_page;
      const currentPage = response.data.current_page;

      this.setData({
        activities: pageNum === 1 ? moreData : [...this.data.activities, ...moreData],
        pageNum: pageNum + 1,  // 更新页码
        loading: false,
        hasMore: currentPage < totalPage, // 判断是否已加载全部数据
      });
    } catch (error) {
      console.error('加载数据失败', error);
      this.setData({
        loading: false,
        hasMore: false, // 失败时视为没有更多数据
      });
    }
  },
  async loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({ loading: true });
      await this.loadData(this.data.pageNum);
    }
  },
})
